package com.lnw.travels.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lnw.travels.entity.Result;
import com.lnw.travels.entity.TPlace;
import com.lnw.travels.entity.TProvince;
import com.lnw.travels.service.PlaceService;
import com.lnw.travels.service.ProvinceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("place")
@CrossOrigin//允许跨域
@Slf4j
public class PlaceController {
    @Autowired
    private PlaceService placeService;

    @Autowired
    private ProvinceService provinceService;

    @Value("${upload.file}")
    private String realPath;

    /**
     * 修改景点方法
     * @param pic
     * @param place
     * @return
     */
    @PostMapping("update")
    public Result updatePlace(MultipartFile pic,TPlace place){
        Result result = new Result();
        try{
            if (pic!=null){
                String extension = FilenameUtils.getExtension(pic.getOriginalFilename());
                String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"."+extension;
                //base64编码
                place.setPicpath(Base64Utils.encodeToString(pic.getBytes()));
                File file = new File(realPath);
                pic.transferTo(new File(file,newFileName));
            }else{
                //保存place对象
                if (placeService.saveOrUpdate(place)){
                    result.setMsg("修改景点信息成功");
                }else{
                    result.setStatus(false).setMsg("修改景点信息失败");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg(e.getMessage());
        }

        return  result;
    }

    /**
     * 根据id查找景点的详细信息，回显给修改页面
     * @param id
     * @return
     */
    @GetMapping("findOne")
    public TPlace findOneById(String id){
        QueryWrapper<TPlace> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        return placeService.getOne(wrapper);
    }

    /**
     * 删除景点
     * 1.根据传来的景点id查到对应的省份id
     * 2.根据省份id查到省份，将对应的景点个数-1，之后执行更新操作
     * 3.更新成功后执行删除操作，
     *
     * 如果先进行删除则会报空指针异常
     * @param id
     * @return
     */
    @GetMapping("delete")
    public Result deletePlace(String id){
        Result result = new Result();
        try {
            QueryWrapper<TPlace> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",id);
            TPlace tPlace = placeService.getOne(queryWrapper);
            //根据景点的省份id查出省份的信息
            QueryWrapper<TProvince>  provinceQueryWrapper = new QueryWrapper<>();
            provinceQueryWrapper.eq("id",tPlace.getProvinceid());
            TProvince tProvince = provinceService.getOne(provinceQueryWrapper);
            //将查出的省份  景点-1并更新
            tProvince.setPlacecounts(tProvince.getPlacecounts()-1);
            if (provinceService.saveOrUpdate(tProvince)){
                placeService.removeById(id);
                result.setMsg("景点删除成功！");
            } else{
                result.setStatus(false).setMsg("景点删除失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 保存景点方法
     * @param pic
     * @param place
     * @return
     */
    @PostMapping("save")
    public Result savePlace(MultipartFile pic,TPlace place){
        Result result = new Result();
        try {
            String extension = FilenameUtils.getExtension(pic.getOriginalFilename());
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"."+extension;
            //base64编码
            place.setPicpath(Base64Utils.encodeToString(pic.getBytes()));
            File file = new File(realPath);
            pic.transferTo(new File(file,newFileName));
            //保存place对象
            placeService.save(place);
            //省份下的景点数量+1
            QueryWrapper<TProvince> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",place.getProvinceid());
            TProvince one = provinceService.getOne(queryWrapper);
            one.setPlacecounts(one.getPlacecounts()+1);
            provinceService.saveOrUpdate(one);

            result.setMsg("保存景点信息成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg(e.getMessage());
        }

        return result;
    }

    /**
     * 查询所有景点信息
     * @return
     */
    @GetMapping("allPlace")
    public Map<String,Object> getAllPlace(Integer page, Integer size,String provinceid){
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<TPlace> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("provinceid",provinceid);
        Page<TPlace> placePage = new Page<>(page , size);
        IPage<TPlace> placeIPage = placeService.page(placePage , queryWrapper);

        long totals = placeIPage.getTotal();
        long totalPage = totals%size==0?totals/size:totals/size+1;

        /*//每页条数
        placeIPage = placeService.selectPage(page,size);*/
        map.put("places",placeIPage.getRecords());
        map.put("totals",totals);
        map.put("totalPage",totalPage);
        map.put("page",placeIPage.getPages());
        return map;

    }

}
